import { useRef, useEffect } from 'react';
import * as echarts from 'echarts';

const EchartCanvas = () => {
    const chartRef = useRef<HTMLCanvasElement>(null);

    const calorieData = [
        { date: '1日', calories: 1800 },
        { date: '2日', calories: 2100 },
        { date: '3日', calories: 1950 },
        { date: '4日', calories: 2200 },
        { date: '5日', calories: 2000 },
        { date: '6日', calories: 2300 },
        { date: '7日', calories: 1900 }
    ];

    const getChartOptions = () => {
        return {
            color: ['#00C2B3'],
            tooltip: {
                trigger: 'axis'
            },
            xAxis: {
                type: 'category',
                data: calorieData.map(item => item.date),
                axisLabel: {
                    color: '#666',
                    formatter: '{value}'
                }
            },
            yAxis: {
                type: 'value',
                axisLabel: {
                    color: '#666'
                }
            },
            series: [
                {
                    data: calorieData.map(item => item.calories),
                    type: 'line',
                    smooth: true,
                    lineStyle: {
                        width: 3
                    }
                }
            ],
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            }
        };
    };

    useEffect(() => {
        const initChart = () => {
            if (chartRef.current) {
                const canvas = chartRef.current;
                // 检查 canvas 是否支持 getContext 方法
                if (typeof canvas.getContext === 'function') {
                    // 设置 canvas 的宽度和高度
                    canvas.width = canvas.offsetWidth;
                    canvas.height = canvas.offsetHeight;

                    const chart = echarts.init(canvas);
                    chart.setOption(getChartOptions());
                    return () => chart.dispose();
                } else {
                    console.error('Canvas does not support getContext method.');
                }
            }
        };

        // 确保在 DOM 完全加载后执行初始化
        if (document.readyState === 'complete') {
            initChart();
        } else {
            window.addEventListener('load', initChart);
            return () => window.removeEventListener('load', initChart);
        }
    }, []);

    return (
        <canvas
            ref={chartRef}
            canvas-id="myChart"
            style={{ width: '100%', height: '300px' }}
        />
    );
};

export default EchartCanvas;